import axios from 'axios';
import { useUserStore } from '../store/user';
import { config } from '../config';

const api = axios.create({
  baseURL: config.api.baseUrl,
  timeout: config.api.timeout,
  headers: {
    'Content-Type': 'application/json',
  }
});

api.interceptors.request.use(config => {
  try {
    const userStore = useUserStore();
    if (userStore.token) {
      config.headers = config.headers || {};
      config.headers.Authorization = `Bearer ${userStore.token}`;
    }
  } catch {}
  return config;
});

api.interceptors.response.use(
  response => response,
  error => {
    if (error.response && error.response.status === 401) {
      try {
        const userStore = useUserStore();
        userStore.logout();
        // 这里不能直接 useRouter()，需用 window.location 替代
        window.location.href = '/login';
      } catch {}
    }
    return Promise.reject(error);
  }
);

export default api; 